import { saveInitAppointSource } from '@/services/api/api-assess-month-emphasize-record';
import { isDev } from '@/utils/dev';
import { CheckCircleOutlined, CheckCircleTwoTone } from '@ant-design/icons';
import {
  ModalForm,
  ProFormCascader,
  ProFormDigit,
  ProFormGroup,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { Alert, Button, Divider, message, Spin } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import UploadDragger from '../components/UploadDragger';

interface AddRecordProveProps {
  onRefurbish: () => void;
  onSave: (data: AssessMonthEmphasizeProveBo.ProveData) => void;
}

const AddRecordProve: React.FC<AddRecordProveProps> = ({ onRefurbish, onSave }) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  /**
   * 加载
   */
  const [loading, setLoadingSate] = useState<boolean>(false);

  /**
   * 提交窗口
   */
  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  /**
   * 初始化Cascader数据
   */

  const [appointSources, setAppointSourcesState] = useState<any>();

  /**
   * 选择 平台账号
   */
  const [selectAppointSource, setSelectAppointSourceState] = useState<any>();

  /**
   * 预备Cascader结构数据
   * @param data
   */
  function readyCascaderData(data: AssessMonthEmphasizeAppointSourceData.TreeAppointSource[]): any {
    const cascaderData = new Array();
    if (data) {
      data.forEach((val) => {
        cascaderData.push({
          label: val.name,
          value: val.id,
          describes: val.describes,
          type: val.type,
          channelId: val.channelId,
          channelName: val.channelName,
          children: readyCascaderData(
            val.children as AssessMonthEmphasizeAppointSourceData.TreeAppointSource[],
          ),
        });
      });
    }
    return cascaderData;
  }

  /**
   * 加载来源详情
   * @param key
   */
  const loadSourceData = async () => {
    try {
      const response = await saveInitAppointSource();
      if (response.code === 0) {
        const cascaderData = readyCascaderData(response.data);
        setAppointSourcesState(cascaderData);
      }
    } catch (error) {}
  };

  const verificationSubmit = (values: any) => {
    if (
      !(values.appointSourceCascaderIds !== undefined && values.appointSourceCascaderIds.length > 0)
    ) {
      message.warning('请选择来源');
      return false;
    }

    if (
      selectAppointSource.channelName == '微信公众号' ||
      selectAppointSource.channelName == '微博' ||
      selectAppointSource.channelName == '抖音' ||
      selectAppointSource.channelName == '今日头条' ||
      selectAppointSource.channelName == '快手' ||
      selectAppointSource.channelName == '哔哩哔哩' ||
      selectAppointSource.channelName == '客户端' ||
      selectAppointSource.channelName == '网站'
    ) {
      if (!(values.url !== undefined)) {
        message.warning('请填写链接');
        return false;
      }

      values.url = values.url.trim();

      if (!(values?.url.length > 0)) {
        message.warning('请填写链接');
        return false;
      }

      if (!values?.url?.startsWith('http')) {
        message.warning('请填写符合要求的链接');
        return false;
      }
    }

    if (!isDev()) {
      //正式线
      if (values.attachments !== undefined && values.attachments.length > 0) {
        values.attachments = values.attachments?.filter((item) => item.status == 'done');
      }

      if (!(values.attachments !== undefined && values.attachments.length > 0)) {
        message.warning('请上传截图等佐证材料');
        return false;
      }
    }

    if (
      selectAppointSource.channelName == '微信公众号' ||
      selectAppointSource.channelName == '微博' ||
      selectAppointSource.channelName == '今日头条' ||
      selectAppointSource.channelName == '客户端' ||
      selectAppointSource.channelName == '网站'
    ) {
      if (!(values.dataReadCount !== undefined && values.dataReadCount > 0)) {
        message.warning('请填写阅读量');
        return false;
      }
    } else {
      if (!(values.dataPlayCount !== undefined && values.dataPlayCount > 0)) {
        message.warning('请填写播放量');
        return false;
      }
    }

    if (!(values.dataLikeCount !== undefined && values.dataLikeCount > 0)) {
      message.warning('请填写点赞量');
      return false;
    }
    if (!(values.dataCollectCount !== undefined && values.dataCollectCount > 0)) {
      message.warning('请填写转发量');
      return false;
    }

    return true;
  };

  return (
    <DrawerForm
      key="add_assess_emphasize_record_drawer_form"
      title={'添加发布平台数据'}
      drawerProps={{
        width: 650,
        maskClosable: false,
        destroyOnClose: true,
      }}
      layout="horizontal"
      formRef={formRef}
      trigger={<Button type="primary">添加发布平台数据</Button>}
      initialValues={{}}
      onOpenChange={(visible) => {
        if (visible) {
          loadSourceData();
          setSelectAppointSourceState(undefined);
        } else {
          setSelectAppointSourceState(undefined);
          setLoadingSate(false);
        }
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              hidden={!(selectAppointSource !== undefined)}
              key="button_release_state_discard"
              icon={<CheckCircleOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              loading={loading}
              onClick={() => {
                const values = formRef.current?.getFieldsValue();

                if (!verificationSubmit(values)) {
                  return;
                }

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_release_state_discard'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              open={modalFormOpen}
              onOpenChange={(open) => {
                setModalFormOpenState(open);
              }}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                  // loading: loading,
                },
              }}
              onFinish={async (values) => {
                setLoadingSate(true);
                setModalFormOpenState(false);
                setTimeout(() => {
                  props.submit();
                }, 100);
                return true;
              }}
            />,
          ];
        },
      }}
      onFinish={async (values) => {
        if (!verificationSubmit(values)) {
          return false;
        }

        let updateData = {
          ...values,
          appointSourceId:
            values.appointSourceCascaderIds[values.appointSourceCascaderIds.length - 1].split('-')[
              values.appointSourceCascaderIds.length - 1
            ],
          appointSourceName: selectAppointSource.label,
          appointSourceType: selectAppointSource.type,
          appointSourceChannelId: selectAppointSource.channelId,
          appointSourceChannelName: selectAppointSource.channelName,
          attachments: values.attachments?.map(
            (item: {
              response: {
                data: {
                  url: any;
                  id: any;
                };
              };
              uid: any;
              name: any;
              type: any;
            }) => {
              return {
                id: item.response.data.id,
                uid: item.uid,
                name: item.name,
                mimeType: item.type,
                url: item.response.data.url,
                status: 'done',
              };
            },
          ),
        };
        onSave(updateData as AssessMonthEmphasizeProveBo.ProveData);
        return true;
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={appointSources === undefined || loading}
      >
        {appointSources != undefined && (
          <>
            <ProFormCascader
              width="xl"
              name="appointSourceCascaderIds"
              label={
                <>
                  <span
                    style={{
                      color: '#ff4d4f',
                      paddingRight: 4,
                    }}
                  >
                    *
                  </span>
                  平台账号
                </>
              }
              extra={'如没有账号请联系 房一：13220207320'}
              fieldProps={{
                displayRender: (labels: string[], selectedOptions?: any[]) => {
                  return labels.map((label, i) => {
                    if (selectedOptions) {
                      const option = selectedOptions[i];
                      if (i === labels.length - 1) {
                        setSelectAppointSourceState(option);
                        return <span key={option.value}>{label}</span>;
                      }
                      return <span key={option.value}>{label} / </span>;
                    } else {
                      return '';
                    }
                  });
                },
                options: appointSources,
                allowClear: true,
                onChange(value: any, selectedOptions: any) {},
                onClear() {},
              }}
            />

            {selectAppointSource !== undefined && (
              <>
                <div
                  style={{
                    width: 552,
                    marginLeft: 52.05,
                    marginBottom: 25,
                  }}
                >
                  <Alert
                    message="为保证记录被正确采纳，请尽量填写相关信息，包括链接、附件、推荐理由"
                    type="warning"
                    showIcon
                  />
                </div>
                <ProFormTextArea
                  width="xl"
                  name="url"
                  hidden={
                    !(
                      selectAppointSource.channelName == '微信公众号' ||
                      selectAppointSource.channelName == '微信视频号' ||
                      selectAppointSource.channelName == '微博' ||
                      selectAppointSource.channelName == '抖音' ||
                      selectAppointSource.channelName == '今日头条' ||
                      selectAppointSource.channelName == '快手' ||
                      selectAppointSource.channelName == '哔哩哔哩' ||
                      selectAppointSource.channelName == '客户端' ||
                      selectAppointSource.channelName == '网站'
                    )
                  }
                  label={
                    <>
                      <span
                        style={{
                          color: '#ff4d4f',
                          paddingRight: selectAppointSource.channelName == '微信视频号' ? 8 : 4,
                        }}
                      >
                        {selectAppointSource.channelName == '微信视频号' ? '' : '*'}
                      </span>
                      链接
                    </>
                  }
                  fieldProps={{
                    showCount: true,
                    allowClear: true,
                    rows: 3,
                    count: { show: true, max: 5000 },
                    style: { resize: 'none' },
                  }}
                  extra={
                    selectAppointSource.channelName == '微信视频号'
                      ? '可填写从"视频号助手"获取来的链接：https://weixin.qq.com/sph/*'
                      : '请填写http开头的链接'
                  }
                />
                <FormItem
                  name="attachments"
                  label={
                    <>
                      <span
                        style={{
                          color: '#ff4d4f',
                          paddingRight: 4,
                        }}
                      >
                        *
                      </span>
                      附件
                    </>
                  }
                >
                  <UploadDragger
                    dragger={true}
                    onPreview={(file) => {}}
                    access={{
                      isPicture: access.传播质效x上报,
                      isVideo: access.传播质效x上报,
                      isOffice: access.传播质效x上报,
                      isOther: access.传播质效x上报,
                    }}
                    url="/assess/month/emphasize/attachment/save"
                    maxCount={10}
                  />
                </FormItem>
                <Divider
                  orientation="left"
                  style={{
                    fontSize: 14,
                    fontWeight: 'bold',
                  }}
                >
                  互动数据
                </Divider>
                <ProFormGroup>
                  <ProFormDigit
                    label={
                      <>
                        <span
                          style={{
                            color: '#ff4d4f',
                            paddingRight: 4,
                          }}
                        >
                          *
                        </span>
                        阅读量
                      </>
                    }
                    hidden={
                      !(
                        selectAppointSource.channelName == '微信公众号' ||
                        selectAppointSource.channelName == '微博' ||
                        selectAppointSource.channelName == '今日头条' ||
                        selectAppointSource.channelName == '客户端' ||
                        selectAppointSource.channelName == '网站'
                      )
                    }
                    name="dataReadCount"
                    width="sm"
                    min={1}
                    max={
                      selectAppointSource.channelName == '微信公众号' ? 99999999999 : 99999999999
                    }
                    extra={
                      selectAppointSource.channelName == '微信公众号'
                        ? '微信数据请到后台查看实际阅读量'
                        : ''
                    }
                  />
                </ProFormGroup>
                <ProFormGroup>
                  <ProFormDigit
                    label={
                      <>
                        <span
                          style={{
                            color: '#ff4d4f',
                            paddingRight: 4,
                          }}
                        >
                          *
                        </span>
                        播放量
                      </>
                    }
                    hidden={
                      !(
                        selectAppointSource.channelName == '微信视频号' ||
                        selectAppointSource.channelName == '抖音' ||
                        selectAppointSource.channelName == '快手' ||
                        selectAppointSource.channelName == '哔哩哔哩'
                      )
                    }
                    name="dataPlayCount"
                    width="sm"
                    min={1}
                    max={99999999999}
                  />
                  <ProFormDigit
                    label={
                      <>
                        <span
                          style={{
                            color: '#ff4d4f',
                            paddingRight: 4,
                          }}
                        >
                          *
                        </span>
                        点赞量
                      </>
                    }
                    name="dataLikeCount"
                    width="sm"
                    min={1}
                    max={999999999}
                  />
                  <ProFormDigit
                    label={
                      <>
                        <span
                          style={{
                            color: '#ff4d4f',
                            paddingRight: 4,
                          }}
                        >
                          *
                        </span>
                        转发量
                      </>
                    }
                    name="dataCollectCount"
                    width="sm"
                    min={1}
                    max={999999999}
                  />
                </ProFormGroup>
                <Divider
                  orientation="left"
                  style={{
                    fontSize: 14,
                    fontWeight: 'bold',
                  }}
                >
                  其他
                </Divider>
                <ProFormTextArea
                  width="xl"
                  name="remarks"
                  label={
                    <>
                      <span
                        style={{
                          color: '#ff4d4f',
                          fontSize: 14,
                          paddingRight: 4,
                        }}
                      >
                        *
                      </span>
                      备注
                    </>
                  }
                  fieldProps={{
                    allowClear: true,
                    rows: 7,
                    count: { show: true, max: 200 },
                  }}
                />
              </>
            )}
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default AddRecordProve;
